package com.example.zy5_project_jetpack.mvp.view.SofaFragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.zy5_project_jetpack.Manager.RetrofitManager;
import com.example.zy5_project_jetpack.R;
import com.example.zy5_project_jetpack.mvp.view.SofaFragment.Adapter.TextAdapter;
import com.example.zy5_project_jetpack.mvp.view.SofaFragment.Bean.ImageBean;
import com.example.zy5_project_jetpack.mvp.view.SofaFragment.Bean.TextBean;
import com.google.gson.Gson;

import java.util.List;

public class TextFragment extends Fragment {

    private TextAdapter textAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_text, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initData();
    }

    private void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String textHttp  = RetrofitManager.getInstance().getTextHttp();
                    if (textHttp != null) {
                        final TextBean textBean = new Gson().fromJson(textHttp, TextBean.class);

                        final List<TextBean.DataBeanX.DataBean> data = textBean.getData().getData();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                textAdapter.addList(data);
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }


    private void initView(View view) {
        RecyclerView recycler_text = view.findViewById(R.id.recycler_text);
        recycler_text.setLayoutManager(new LinearLayoutManager(getActivity()));
        textAdapter = new TextAdapter(getActivity());
        recycler_text.addItemDecoration(new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL));
        recycler_text.setAdapter(textAdapter);
    }
}